package com.admission.service;

import java.io.File;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.admission.dao.AttachmentDao;
import com.admission.model.Attachment;
import com.admission.util.DeleteFile;
import com.admission.util.XmlUtils;

@Transactional
@Repository
public class AttachmentManager {
	private AttachmentDao attachmentDao;

	/**
	 * 通过id找唯一对象，无返回null
	 * 
	 * @param id
	 * @return
	 */
	public Attachment getAttachmentById(String id) {
		return attachmentDao.findUniqueBy("id", id);
	}

	/**
	 * 保存、更新
	 * 
	 * @param Entity
	 * @return
	 */
	public void save(Attachment entity, String url) throws Exception {
		String serverrealPath = ServletActionContext.getServletContext()
				.getRealPath("/upload");
		if (url != null) {
			File file = new File(serverrealPath + File.separator
					+ entity.getUrl());
			DeleteFile.deleteByFile(file);// 删除源文件
			entity.setUrl(url);
		}
		attachmentDao.save(entity);
	}

	/**
	 * 创建主页xml
	 */
	public void createXml() {
		Page<Attachment> attachmentPage = new Page<Attachment>(4);
		attachmentPage.setOrder(Page.DESC);
		attachmentPage.setOrderBy("inputTime");
		getPage(attachmentPage);
		
		String path = ServletActionContext.getServletContext().getRealPath(
				"/WEB-INF");
		path += "/other/mainpage-attachmentPage.xml";
		XmlUtils.create(attachmentPage.getResult(), path);
	}

	/**
	 * 批量删除
	 * 
	 * @param Entity
	 * @return
	 */
	public void deleteById(String ids) throws Exception {
		String serverrealPath = ServletActionContext.getServletContext()
				.getRealPath("/upload");
		for (String id : ids.split(",")) {
			Attachment entity = this.getAttachmentById(id.trim());
			File file = new File(serverrealPath + File.separator
					+ entity.getUrl());
			DeleteFile.deleteByFile(file);// 删除源文件
			attachmentDao.delete(id.trim());
		}
	}

	/**
	 * 通过page查询结果
	 * 
	 * @param page
	 * @param filters
	 * @return
	 */
	public Page<Attachment> getPage(Page<Attachment> page) {
		return attachmentDao.getAll(page);
	}

	public Page<Attachment> getByFilter(final Page<Attachment> page,
			List<PropertyFilter> filters) {
		return attachmentDao.findPage(page, filters);
	}

	public String genNewFileName(String fileName) {
		return fileName;

	}

	public AttachmentDao getAttachmentDao() {
		return attachmentDao;
	}

	@Autowired
	public void setAttachmentDao(AttachmentDao attachmentDao) {
		this.attachmentDao = attachmentDao;
	}

}
